<template>
	<view class="course-edit">
		<!-- 基本信息 -->
		<view class="section">
			<view class="section-title">基本信息</view>
			<view class="form-item">
				<text class="label required">课程标题</text>
				<input class="input" v-model="courseInfo.title" placeholder="请输入课程标题" maxlength="50" />
				<text class="word-count">{{courseInfo.title.length}}/50</text>
			</view>
			<view class="form-item">
				<text class="label required">课程分类</text>
				<picker mode="selector" :range="categories" range-key="name" @change="handleCategoryChange">
					<view class="picker">
						<text :class="{'placeholder': !courseInfo.categoryId}">{{ courseInfo.categoryId ? getCategoryName(courseInfo.categoryId) : '请选择分类' }}</text>
						<text class="iconfont icon-arrow-down"></text>
					</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="label required">课程封面</text>
				<view class="upload-box" @click="chooseImage">
					<image v-if="courseInfo.imageUrl" :src="courseInfo.imageUrl" mode="aspectFill" class="preview-image"></image>
					<view v-else class="upload-placeholder">
						<text class="iconfont icon-camera"></text>
						<text>点击上传封面</text>
					</view>
				</view>
				<text class="upload-tip">建议尺寸：750x422px，支持jpg、png格式</text>
			</view>
			<view class="form-item">
				<text class="label required">课程价格</text>
				<input class="input" type="digit" v-model="courseInfo.price" placeholder="请输入课程价格" />
				<text class="unit">元</text>
			</view>
			<view class="form-item">
				<text class="label required">课程地点</text>
				<input class="input" v-model="courseInfo.location" placeholder="请输入课程地点" />
			</view>
			<view class="form-item">
				<text class="label required">课程时长</text>
				<input class="input" v-model="courseInfo.duration" placeholder="请输入课程时长" />
				<text class="unit">小时</text>
			</view>
			<view class="form-item">
				<text class="label required">适合人群</text>
				<input class="input" v-model="courseInfo.suitableFor" placeholder="请输入适合人群" />
			</view>
		</view>

		<!-- 课程规划 -->
		<view class="section">
			<view class="section-title">课程规划</view>
			<view class="form-item">
				<text class="label required">课程安排</text>
				<textarea class="textarea" v-model="courseInfo.schedule" placeholder="请输入课程安排，每行一个时间段" />
			</view>
			<view class="form-item">
				<text class="label required">注意事项</text>
				<textarea class="textarea" v-model="courseInfo.notes" placeholder="请输入注意事项，每行一条" />
			</view>
			<view class="form-item">
				<text class="label required">所需物品</text>
				<textarea class="textarea" v-model="courseInfo.requiredItems" placeholder="请输入所需物品，用逗号分隔" />
			</view>
			<view class="form-item">
				<text class="label required">课程目标</text>
				<textarea class="textarea" v-model="courseInfo.objectives" placeholder="请输入课程目标，每行一个目标" />
			</view>
		</view>

		<!-- 课程详情 -->
		<view class="section">
			<view class="section-title">课程详情</view>
			<view class="form-item">
				<text class="label required">课程介绍</text>
				<editor 
					id="editor" 
					class="editor" 
					:placeholder="'请输入课程介绍'"
					@ready="onEditorReady"
					@input="onContentChange"
				></editor>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn" @click="handleSubmit">保存</view>
	</view>
</template>

<script>
const db = uniCloud.database()
export default {
	data() {
		return {
			courseId: '',
			// 本地固定的分类列表
			categories: [
			//	{ _id: '7', name: '亲子推荐' },
				{ _id: '1', name: '编程开发' },
				{ _id: '2', name: '设计创作' },
				{ _id: '3', name: '语言学习' },
				{ _id: '4', name: '考试认证' },
				{ _id: '5', name: '职场技能' },
				{ _id: '6', name: '兴趣爱好' }
				
			],
			courseInfo: {
				title: '',
				categoryId: '',
				imageUrl: '',
				price: '',
				location: '',
				duration: '',
				suitableFor: '',
				schedule: '',
				notes: '',
				requiredItems: '',
				objectives: '',
				content: '' // 富文本内容
			},
			editorCtx: null
		}
	},
	
	onLoad(options) {
		if (options.id) {
			this.courseId = options.id
			this.loadCourseDetail()
		}
	},
	
	methods: {
		// 获取分类名称
		getCategoryName(categoryId) {
			const category = this.categories.find(item => item._id === categoryId)
			return category ? category.name : ''
		},
		
		// 分类选择变化
		handleCategoryChange(e) {
			this.courseInfo.categoryId = this.categories[e.detail.value]._id
		},
		
		// 加载课程详情
		async loadCourseDetail() {
			try {
				uni.showLoading({
					title: '加载中...'
				})
				
				const res = await uniCloud.callFunction({
					name: 'getCourseDetail',
					data: { courseId: this.courseId }
				})
				
				if (res.result.code === 0) {
					this.courseInfo = res.result.data
					// 设置富文本内容
					if (this.editorCtx && this.courseInfo.content) {
						this.editorCtx.setContents({
							html: this.courseInfo.content
						})
					}
				} else {
					uni.showToast({
						title: res.result.msg || '加载失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载课程详情失败', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 选择图片
		async chooseImage() {
			try {
				const res = await uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera']
				})
				
				if (res.tempFilePaths && res.tempFilePaths.length > 0) {
					uni.showLoading({
						title: '上传中...'
					})
					
					// 上传图片到云存储
					const uploadRes = await uniCloud.uploadFile({
						filePath: res.tempFilePaths[0],
						cloudPath: `course/${Date.now()}-${Math.random().toString(36).slice(-6)}.${res.tempFilePaths[0].split('.').pop()}`
					})
					
					this.courseInfo.imageUrl = uploadRes.fileID
				}
			} catch (error) {
				console.error('选择图片失败', error)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 编辑器准备就绪
		onEditorReady() {
			uni.createSelectorQuery().select('#editor').context((res) => {
				this.editorCtx = res.context
				// 如果有内容，设置内容
				if (this.courseInfo.content) {
					this.editorCtx.setContents({
						html: this.courseInfo.content
					})
				}
			}).exec()
		},
		
		// 编辑器内容变化
		onContentChange(e) {
			this.courseInfo.content = e.detail.html
		},
		
		// 表单验证
		validateForm() {
			// 编辑模式不需要验证
			if (this.courseId) {
				return true
			}
			
			// 新建模式需要验证
			const requiredFields = {
				title: '课程标题',
				categoryId: '课程分类',
				imageUrl: '课程封面',
				price: '课程价格',
				location: '课程地点',
				duration: '课程时长',
				suitableFor: '适合人群',
				schedule: '课程安排',
				notes: '注意事项',
				requiredItems: '所需物品',
				objectives: '课程目标',
				content: '课程介绍'
			}
			
			for (const [field, label] of Object.entries(requiredFields)) {
				if (!this.courseInfo[field]) {
					uni.showToast({
						title: `请${field === 'imageUrl' ? '上传' : '输入'}${label}`,
						icon: 'none'
					})
					return false
				}
			}
			
			// 验证价格
			if (isNaN(this.courseInfo.price) || Number(this.courseInfo.price) <= 0) {
				uni.showToast({
					title: '请输入有效的课程价格',
					icon: 'none'
				})
				return false
			}
			
			// 验证时长
			if (isNaN(this.courseInfo.duration) || Number(this.courseInfo.duration) <= 0) {
				uni.showToast({
					title: '请输入有效的课程时长',
					icon: 'none'
				})
				return false
			}
			
			return true
		},
		
		// 提交表单
		async handleSubmit() {
			// 表单验证
			if (!this.validateForm()) {
				return
			}
			
			try {
				uni.showLoading({
					title: '保存中...'
				})
				
				// 处理数据
				const submitData = {
					...this.courseInfo,
					price: Number(this.courseInfo.price),
					duration: Number(this.courseInfo.duration)
				}
				
				const res = await uniCloud.callFunction({
					name: this.courseId ? 'updateCourse' : 'addCourse',
					data: {
						courseId: this.courseId,
						courseInfo: submitData
					}
				})
				
				if (res.result.code === 0) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					throw new Error(res.result.msg)
				}
			} catch (error) {
				console.error('保存课程失败', error)
				uni.showToast({
					title: error.message || '保存失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.course-edit {
	min-height: 100vh;
	background-color: #f8f9fc;
	padding-bottom: 120rpx;
}

.section {
	background-color: #fff;
	margin-bottom: 20rpx;
	padding: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.form-item {
	margin-bottom: 30rpx;
	position: relative;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
	
	&.required::before {
		content: '*';
		color: #ff4d4f;
		margin-right: 4rpx;
	}
}

.input {
	width: 100%;
	height: 80rpx;
	background-color: #f8f9fc;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
}

.textarea {
	width: 100%;
	height: 200rpx;
	background-color: #f8f9fc;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
}

.picker {
	width: 100%;
	height: 80rpx;
	background-color: #f8f9fc;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	
	.placeholder {
		color: #999;
	}
}

.upload-box {
	width: 100%;
	height: 400rpx;
	background-color: #f8f9fc;
	border-radius: 8rpx;
	overflow: hidden;
	position: relative;
}

.preview-image {
	width: 100%;
	height: 100%;
}

.upload-placeholder {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	color: #999;
	
	.iconfont {
		font-size: 60rpx;
		margin-bottom: 10rpx;
	}
}

.upload-tip {
	font-size: 24rpx;
	color: #999;
	margin-top: 10rpx;
}

.word-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 10rpx;
}

.unit {
	font-size: 28rpx;
	color: #666;
	margin-left: 10rpx;
}

.editor {
	width: 100%;
	height: 400rpx;
	background-color: #f8f9fc;
	border-radius: 8rpx;
}

.submit-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	line-height: 100rpx;
	text-align: center;
	background: linear-gradient(135deg, #4a6ee0, #3a5bc7);
	color: #fff;
	font-size: 32rpx;
}

/* 图标字体 */
@font-face {
	font-family: "iconfont";
	src: url('//at.alicdn.com/t/font_3456789_abcdef.woff2') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-camera:before {
	content: "\e7d7";
}

.picker .icon-arrow-down {
	font-size: 24rpx;
	color: #999;
}
</style> 